package com.demo.config.apache.ocr;

import com.demo.config.apache.ocr.OpenCV.OpenCVTest;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Tess4j Ocr 图片识别文字测试示例
 */
@Slf4j
public class OcrTest {

	private static final String DEFAULT_LANG = "chi_sim";

	private static final String DATA_PATH = "D:\\job\\private\\demo\\src\\main\\resources\\tessdata";

	// private static final String IMAGE_PATH = "D:\\file\\1709867284482.jpg";
	private static final String IMAGE111_PATH = "D:\\file\\test3.jpg";

	private static final String IMAGE3_PATH = "D:\\file\\test\\test44.png";

	private static final String File_PATH = "D:\\file\\test\\";

	private static final String IMAGE_PATH = "D:\\file\\images\\test44.png";

	public static void main(String[] args) throws Exception {
		// =================================OCR--百度====================================
		// 读取图片文件
		// InputStream inStream = new FileInputStream(IMAGE_PATH);
		//// // 将输入流转换为BufferedImage对象
		// BufferedImage bImage = ImageIO.read(inStream);
		// String ocrStr = OcrUtil.ocrSense(bImage);
		//
		// System.out.println(ocrStr);

		// =================================OCR--tess4j====================================

		// 图片识别文字-去除噪点后的图片
		// Tess4jUtil.recognizeText(IMAGE_PATH);
		// Tess4jUtil.testZh(IMAGE_PATH);

		ocrDemo(IMAGE_PATH);

	}

	/**
	 * 图片文字识别
	 */
	// 定义一个名为ocrDemo的静态方法
	public static void ocrDemo(String imagePath) {
		// 创建一个Tesseract实例
		Tesseract instance = new Tesseract();
		// 设置数据路径
		instance.setDatapath(DATA_PATH);
		// 设置用户自定义的DPI值
		instance.setVariable("user_defined_dpi", "300");
		// 设置识别语言
		instance.setLanguage(DEFAULT_LANG);

		try {
			// 记录开始时间
			long startTime = System.currentTimeMillis();
			// 将图片去噪并转换为BufferedImage对象
			// BufferedImage bImage = ClearImageUtil.cleanImage(imagePath);
			// 将图片通过OpenCV灰度化、二进制并转换为BufferedImage对象
			BufferedImage bImage = OpenCVTest.ertyu222(imagePath);
			// 使用Tesseract进行OCR识别
			String result = instance.doOCR(bImage);
			// 输出识别结果
			System.out.println(result);

			// 记录结束时间
			long endTime = System.currentTimeMillis();
			// 计算耗时（单位：秒）
			long seconds = (endTime - startTime) / 1000;
			// 输出耗时
			System.out.println("共用时：" + seconds + "秒");

		}
		catch (TesseractException | IOException e) {
			// 抛出运行时异常
			throw new RuntimeException(e);
		}

	}

}
